import React, {useEffect , useState} from 'react';
import { Modal, Form, Input, Select , Button, message, Spin} from 'antd';
import { FormInstance } from 'antd/lib/form';
import { TableListItem } from '../data.d';
import { programDetail,checkedAccount } from '../service';

interface CreateFormProps {
  modalVisible: boolean;
  onCancel: () => void;
  onSubmit: (values: TableListItem) => void;
  id:number;
}

const { Option } = Select;

const layout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 16 },
};

const formRef = React.createRef<FormInstance>();

// 验证账号是否已经被添加过
const checkName = (id: number, value: string, topOrgId:number) => {
  // rules自定义的验证方法
  // debounce((id,value,topOrgId)=>{
    return new Promise((resolve, reject) => {
      checkedAccount({ id: id, name: value, topOrgId:topOrgId })
        .then((res) => {
          if (res.code === 200) {
            let data = res.data;
            if (data == 0) {
              resolve(true);
            } else {
              resolve(false);
            }
            resolve(res.data);
          } else resolve(false);
        })
        .catch((error) => {
          reject(error);
        });
    });
  // }, 500);
};

const onResolutionChange = (value:string) => {};
const onTemplateChange = (value) => {};

const CreateForm: React.FC<CreateFormProps> = (props) => {
  const { modalVisible, id, onSubmit, onCancel } = props;

  const [spinning, setSpinning] = useState<boolean>(false);
  const [loading, setLoading] = useState<boolean>(false);
  const [topOrgId, setTopOrgId] = useState<number>(0);

  const [form] = Form.useForm();

  useEffect(() => {
    if(modalVisible){
      setLoading(false);
      if(id){
        setSpinning(true);
        new Promise((resolve, reject) => { //节目详情
          programDetail(id)
            .then((res) => {
              if(res){
                if (res.code === 200) {
                  let values = res.data;
                  form.setFieldsValue({
                    id: id,
                    name: values.name,
                    resolution: values.resolutionWidth + 'x' + values.resolutionHeight,
                    playModel:values.playModel,
                    // deviceType: values.deviceType,
                  });
                  setTopOrgId(values.topOrgId);
                  resolve(true);
                } else {
                  message.error('请求失败，' + res.message);
                  resolve(false);
                }
              }
              setSpinning(false);
            })
            .catch((error) => {
              message.error('请求失败');
              reject(error);
            });
        });
      }else{
        setTopOrgId(JSON.parse(localStorage.getItem("user")).topOrgId);
        form.resetFields();
      }
    }
    
},[modalVisible]);

  const handleFinish = (values: { [key: string]: any }) => {
    if (onSubmit) {
      setLoading(true);
      onSubmit(values as TableListItem);
    }
  };

  const handleUpdate = () => {
    if (!form) return;
    form.submit();
  };

  const renderContent = () => {
    return (
      <>
        <Form.Item name="id" style={{ display: 'none' }}></Form.Item>
        <Form.Item
          name="name"
          label="名称"
          rules={[
            { required: true, max: 16, whitespace: true},
            {
              validator: (rule, value, callback) => {
                if(!value){
                  callback();
                }
                checkName(id, value, topOrgId).then((res) => {
                  if (res) {
                    callback();
                  } else {
                    callback('节目名称已存在');
                  }
                });
              },
              
              validateTrigger:['onBlur']
            },
            
          ]}
        >
          <Input placeholder="请输入节目名称" />
        </Form.Item>
        <Form.Item name="resolution" label="分辨率" rules={[{ required: true, message:'请选择分辨率' }]} style={{display:id?"none":"flex"}}>
          <Select placeholder="请选择分辨率" onChange={onResolutionChange} allowClear>
            <Option value="1920x1080">1920x1080</Option>
            <Option value="1080x1920">1080x1920</Option>
            <Option value="other">自定义</Option>
          </Select>
        </Form.Item>
        <Form.Item
          noStyle
          shouldUpdate={(prevValues, currentValues) =>
            prevValues.resolution !== currentValues.resolution
          }
        >
          {({ getFieldValue }) => {
            return getFieldValue('resolution') === 'other' ? (
              <Form.Item name="resolutionWidth" label="宽度" rules={[{ required: true }]}>
                <Input placeholder="px" />
              </Form.Item>
            ) : null;
          }}
        </Form.Item>
        <Form.Item
          noStyle
          shouldUpdate={(prevValues, currentValues) =>
            prevValues.resolution !== currentValues.resolution
          }
        >
          {({ getFieldValue }) => {
            return getFieldValue('resolution') === 'other' ? (
              <Form.Item
                name="resolutionHeight"
                label="高度"
                rules={[{ required: true }]}
              >
                <Input placeholder="px" />
              </Form.Item>
            ) : null;
          }}
        </Form.Item>
        <Form.Item name="playModel" label="播放模式" rules={[{ required: true, message:'请选择播放模式' }]} style={{display:id?"none":"flex"}}>
          <Select placeholder="请选择播放模式" onChange={onResolutionChange} allowClear>
            <Option value="H5">H5</Option>
            <Option value="android">android</Option>
          </Select>
        </Form.Item>
        <Form.Item 
          name="deviceType" 
          label="设备类型"
          initialValue="LCD"
          style={{display:"none"}}
          rules={[{ required: true }]} >
          <Select placeholder="请选择设备类型" allowClear>
            <Option value="LCD">LCD</Option>
            <Option value="LED">LED</Option>
          </Select>
        </Form.Item>
        {/* <Form.Item
          name="template"
          label="模板"
          // rules={[{ required: true }]}
        >
          <Select placeholder="请选择模板" onChange={onTemplateChange} allowClear>
            <Option value="0">无模板</Option>
            <Option value="1">模板1</Option>
            <Option value="2">模板2</Option>
          </Select>
        </Form.Item>
        <Form.Item
          noStyle
          shouldUpdate={(prevValues, currentValues) =>
            prevValues.template !== currentValues.template
          }
        >
          {({ getFieldValue }) => {
            return getFieldValue('template') != 0 && getFieldValue('template') != undefined ? (
              <Form.Item
                name="dataSource"
                label="数据源"
                // rules={[{ required: true }]}
                className={styles.dataSource}
              >
                <Input.Group compact>
                  <Form.Item
                    name={['organization', 'name']}
                    noStyle
                    rules={[{ required: true, message: '请选择机构' }]}
                  >
                    <Select placeholder="请选择所属机构" style={{ width: '50%' }}>
                      <Option value="1">所属机构1</Option>
                      <Option value="2">所属机构2</Option>
                    </Select>
                  </Form.Item>
                  <Form.Item
                    name={['organization', 'field']}
                    noStyle
                    rules={[{ required: true, message: '请选择所属机构字段' }]}
                  >
                    <ul>
                      <li>
                        <Input placeholder="商品1-item code" />
                      </li>
                      <li>
                        <Input placeholder="商品2-item code" />
                      </li>
                    </ul>
                  </Form.Item>
                </Input.Group>
              </Form.Item>
            ) : null;
          }}
        </Form.Item> */}
        </>
    );
  };
  return (
    <Modal 
      destroyOnClose 
      title={id?"重命名":"新建节目"}
      visible={modalVisible}
      onCancel={onCancel}
      footer={[
        <>
        <Button type="default" onClick={onCancel}>取消</Button>
        <Button type="primary" loading={loading} onClick={handleUpdate}>保存</Button>
        </>
      ]}
    >
      <Spin spinning={spinning}>
        <Form 
          {...layout} 
          ref={formRef} 
          form={form}
          onFinish={handleFinish}
        >
          {renderContent()}
        </Form>
      </Spin>
    </Modal>
  );
};

export default CreateForm;
